# unknown_person.py - 陌生人处理模块（持续6秒后才开始录像）
import cv2
import time
import os
from datetime import datetime
from untils.tts import play
from email_sender import send_alert_async

# 状态变量
unknown_detected_time = None
recording = False
video_writer = None
unknown_persist_threshold = 5  # 陌生人持续8秒后才开始录像
warning_played = False
last_warning_time = 0
warning_interval = 2  # 警告间隔时间（秒）

def start_recording(frame_width, frame_height):
    """开始录像"""
    global recording, video_writer
    
    if recording:
        return
        
    recording = True
    fourcc = cv2.VideoWriter_fourcc(*'XVID') 
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") 
    output_file = f"recordings/unknown_person_{timestamp}.avi"
        
    # 确保录像目录存在
    os.makedirs("recordings", exist_ok=True)
    
    video_writer = cv2.VideoWriter(
        output_file, fourcc, 20.0, (frame_width, frame_height)
    )
    
    print(f"开始录像: {output_file}")
    # 添加邮件提醒功能 - 在开始录像后发送预警邮件
    send_alert_async(
        alert_type="陌生人检测",
        location="门口",
        additional_info=f"系统已开始录像，视频文件: {output_file}"
    )
    return True

def stop_recording():
    """停止录像"""
    global recording, video_writer
    
    if recording:
        recording = False
        video_writer.release()
        print("录像已停止")
    return True

def is_recording():
    """检查是否正在录像"""
    return recording

def play_warning_sound():
    """播放警告声音"""
    global warning_played, last_warning_time
    
    current_time = time.time()
    if not warning_played or (current_time - last_warning_time) > warning_interval:
        # 使用异步播放，不阻塞主线程
        play("注意！检测到陌生人靠近，请立即确认身份")
        warning_played = True
        last_warning_time = current_time
        return True
    return False

def handle_unknown_person(frame, face_locations, face_names, frame_width, frame_height):
    """处理陌生人检测"""
    global unknown_detected_time, warning_played
    
    current_time = time.time()
    
    # 检查是否有陌生人
    has_unknown = any(name == "unknown" for name in face_names)
    
    if has_unknown:
        if unknown_detected_time is None:
            unknown_detected_time = current_time
            print("检测到陌生人!")
            play_warning_sound()
        
        # 计算陌生人已停留时间
        elapsed_time = current_time - unknown_detected_time
        
        # 显示剩余时间直到开始录像
        if elapsed_time < unknown_persist_threshold:
            remaining_time = unknown_persist_threshold - elapsed_time
            cv2.putText(frame, f"录像倒计时: {remaining_time:.1f}s", (10, 30), 
                       cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
        
        # 定期播放警告声音
        if elapsed_time > 0 and elapsed_time < unknown_persist_threshold:
            play_warning_sound()
        
        # 检查陌生人是否停留超过8秒
        if elapsed_time >= unknown_persist_threshold and not recording:
            print("陌生人停留时间超过8秒，开始录像!")
            start_recording(frame_width, frame_height)
    else:
        # 没有陌生人，重置计时器和警告状态
        unknown_detected_time = None
        warning_played = False
        if recording:
            stop_recording()
    
    # 在帧上绘制识别结果
    for (x, y, w, h), name in zip(face_locations, face_names):
        # 绘制人脸框
        color = (0, 0, 255) if name == "unknown" else (0, 255, 0)
        cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
        
        # 绘制标签
        cv2.rectangle(frame, (x, y - 35), (x + w, y), color, cv2.FILLED)
        font = cv2.FONT_HERSHEY_DUPLEX
        cv2.putText(frame, name, (x + 6, y - 6), font, 1.0, (255, 255, 255), 1)
    
    return frame

def record_frame(frame):
    """录制当前帧"""
    if recording:
        video_writer.write(frame)
        
def get_remaining_time():
    """获取距离开始录像的剩余时间"""
    global unknown_detected_time
    if unknown_detected_time is None:
        return 0
    
    elapsed_time = time.time() - unknown_detected_time
    if elapsed_time < unknown_persist_threshold:
        return unknown_persist_threshold - elapsed_time
    return 0